package com.iweb.util;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * @author WuYongheng
 * @date 2021/11/28
 * @description
 */
public class DBHelper {
    // 数据库连接工具类
    private static String url;
    private static String username;
    private static String password;
    private static String driverClassName;

    static {
        init();
    }

    /**
     * 获取数据库连接信息
     */
    private static void init() {
        Properties prop = new Properties();
        InputStream is = DBHelper.class.getClassLoader().getResourceAsStream("db.properties");
        try {
            prop.load(is);
            url = prop.getProperty("jdbc.url");
            username = prop.getProperty("jdbc.username");
            password = prop.getProperty("jdbc.password");
            driverClassName = prop.getProperty("jdbc.driverClassName");
            // 加载驱动
            Class.forName(driverClassName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 自定义获取数据库连接对象
     *
     * @return
     * @throws Exception
     */
    public static Connection getConnection() throws SQLException {
        Connection connection = DriverManager.getConnection(url, username, password);
        return connection;
    }

    public static void close(Connection connection) throws SQLException {
        if (connection != null) {
            connection.close();
        }
    }

    public static void close(Statement statement,
                             Connection connection) throws SQLException {
        if (statement != null) {
            statement.close();
        }
        if (connection != null) {
            connection.close();
        }
    }

    public static void close(ResultSet resultSet,
                             Statement statement,
                             Connection connection) throws SQLException {
        if (resultSet != null) {
            resultSet.close();
        }
        if (statement != null) {
            statement.close();
        }
        if (connection != null) {
            connection.close();
        }
    }
}
